﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mtexlm
{
	public partial class MainForm : Form
	{
		private bool _saved = true;
		private string _filename = "";

		private Point _ptmove;
		private Point _ptdest;
		private Size _size;
		private Bitmap _bmp, _tbp;

		public MainForm()
		{
			InitializeComponent();

			cboNewSizeWidth.SelectedIndex = 6;
			cboNewSizeHeight.SelectedIndex = 6;
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			CreateCanvas();
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!_saved)
			{
				System.Windows.Forms.DialogResult res = MessageBox.Show("저장하지 않았습니다만, 종료하시겠습니까?", "확인", MessageBoxButtons.YesNo);
				if (res == System.Windows.Forms.DialogResult.No)
				{
					e.Cancel = true;
					return;
				}
			}
		}

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{

		}

		private void lstImages_DragOver(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
				e.Effect = DragDropEffects.Copy;
		}

		private void lstImages_DragDrop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				bool needsize = lstImages.Items.Count == 0;
				string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

				ReadImageForm frm = new ReadImageForm(files);
				frm.ShowDialog();

				List<ListViewItem> items = frm.Items;
				List<Bitmap> bmps = frm.Bmps;
				int count = items.Count;

				if (count == bmps.Count && count > 0)
				{
					lstImages.BeginUpdate();

					ImageList il = lstImages.LargeImageList;
					if (il == null)
					{
						il = new ImageList();
						il.ImageSize = new System.Drawing.Size(64, 64);
						lstImages.LargeImageList = il;
					}

					int nil = il.Images.Count;

					for (int i = 0; i < count; i++)
					{
						ListViewItem li = items[i];
						li.ImageIndex = nil++;
						lstImages.Items.Add(li);

						il.Images.AddStrip(bmps[i]);
					}

					SortList();

					lstImages.EndUpdate();

					if (needsize)
					{
						Bitmap bmp = (Bitmap)items[0].Tag;
						nudMoveWidth.Value = bmp.Width;
						nudMoveHeight.Value = bmp.Height;
					}
				}
			}
		}

		private void SortList()
		{
			int max = lstImages.Items.Count;

			ListViewItem[] lis = new ListViewItem[max];

			for (int i = 0; i < max; i++)
				lis[i] = lstImages.Items[i];

			if (SBCS.Test)
			{
				Array.Sort(lis, delegate(ListViewItem i1, ListViewItem i2)
				{
					string s1 = (string)((Bitmap)i1.Tag).Tag;
					string s2 = (string)((Bitmap)i2.Tag).Tag;
					return SBCS.k_strnatcasecmp(s1, s2);
				});
			}
			else
			{
				Array.Sort(lis, delegate(ListViewItem i1, ListViewItem i2)
				{
					string s1 = (string)((Bitmap)i1.Tag).Tag;
					string s2 = (string)((Bitmap)i2.Tag).Tag;
					return s1.CompareTo(s2);
				});
			}

			lstImages.SelectedItems.Clear();

			lstImages.BeginUpdate();
			lstImages.Items.Clear();

			foreach (ListViewItem li in lis)
				lstImages.Items.Add(li);

			lstImages.EndUpdate();
		}

		private void btnDeleteList_Click(object sender, EventArgs e)
		{
			if (lstImages.SelectedItems.Count > 0)
			{
				foreach (ListViewItem li in lstImages.SelectedItems)
					lstImages.Items.Remove(li);

				lstImages.SelectedItems.Clear();
			}

			if (lstImages.Items.Count == 0)
			{
				lstImages.LargeImageList = null;
				nudMoveWidth.Value = 32;
				nudMoveHeight.Value = 32;
			}
		}

		private void btnClearList_Click(object sender, EventArgs e)
		{
			lstImages.Items.Clear();
			lstImages.LargeImageList = null;
			nudMoveWidth.Value = 32;
			nudMoveHeight.Value = 32;
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
			if (_saved)
				return;

			SaveFileDialog dlg = new SaveFileDialog();
			dlg.Filter = "png 파일 (*.png)|*.png|모든 파일 (*.*)|*.*";
			dlg.FilterIndex = 1;
			dlg.RestoreDirectory = true;
			dlg.OverwritePrompt = true;
			dlg.AddExtension = true;
			dlg.FileName = _filename;

			if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
				return;

			_filename = dlg.FileName;

			_bmp.Save(_filename, System.Drawing.Imaging.ImageFormat.Png);

			_saved = true;
		}

		private void btnCreateNew_Click(object sender, EventArgs e)
		{
			if (!_saved)
			{
				System.Windows.Forms.DialogResult res = MessageBox.Show("저장하지 않았습니다만, 계속하렵니까?", "확인", MessageBoxButtons.YesNo);
				if (res == System.Windows.Forms.DialogResult.No)
					return;
			}

			CreateCanvas();
		}

		private void pxWork_MouseMove(object sender, MouseEventArgs e)
		{
			float rx = (float)e.X / (float)pxWork.Width;
			float ry = (float)e.Y / (float)pxWork.Height;
			float tx = rx * (float)_size.Width;
			float ty = ry * (float)_size.Height;
			float ux = tx / (float)nudMoveWidth.Value;
			float uy = ty / (float)nudMoveHeight.Value;

			lblInfo.Text = string.Format("{0}x{1} ({2}x{3}) [{4}x{5}]",
				e.X, e.Y, (int)tx, (int)ty, (int)ux, (int)uy);

			_ptmove.X = (int)ux;
			_ptmove.Y = (int)uy;

		}

		private void pxWork_MouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == System.Windows.Forms.MouseButtons.Left)
			{
				_ptdest = _ptmove;
				UpdateCanvas();
			}
		}

		private void CreateCanvas()
		{
			_size = new Size(
				Convert.ToInt32(cboNewSizeWidth.SelectedItem),
				Convert.ToInt32(cboNewSizeHeight.SelectedItem));
			_bmp = new Bitmap(_size.Width, _size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
			_tbp = new Bitmap(_size.Width, _size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

			UpdateCanvas();

			_saved = true;
			_filename = "";
		}

		private void UpdateCanvas()
		{
			int w = (int)nudMoveWidth.Value;
			int h = (int)nudMoveHeight.Value;
			int tx = _ptdest.X * w;
			int ty = _ptdest.Y * h;

			using (Graphics g = Graphics.FromImage(_tbp))
			{
				g.Clear(Color.Transparent);
				g.DrawImage(_bmp, 0, 0, _size.Width, _size.Height);

				g.DrawRectangle(Pens.Blue, tx, ty, w, h);
			}

			pxWork.Image = _tbp;
		}

		private void btnListPaste_Click(object sender, EventArgs e)
		{
			if (lstImages.SelectedItems.Count == 0)
				return;

			_saved = false;

			int x = _ptdest.X * (int)nudMoveWidth.Value;
			int y = _ptdest.Y * (int)nudMoveHeight.Value;

			using (Graphics g=Graphics.FromImage(_bmp))
			{
				foreach (ListViewItem li in lstImages.SelectedItems)
				{
					Bitmap b = (Bitmap)li.Tag;

					if ((x + b.Width) > _size.Width)
					{
						y += b.Height;
						if (y > _size.Height)
							break;

						x = 0;
					}

					g.FillRectangle(Brushes.Transparent, x, y, b.Width, b.Height);
					g.DrawImage(b, x, y, b.Width, b.Height);

					x += b.Width;
				}
			}

			UpdateCanvas();
		}

		private void MainForm_KeyDown(object sender, KeyEventArgs e)
		{
			System.Diagnostics.Debug.WriteLine(e.KeyCode.ToString());
		}
	}
}
